import React, {Component} from 'react'
import {View, Text, FlatList, Image, ScrollView, TouchableOpacity, TextInput, Switch, Alert, ImageBackground} from 'react-native'
import {GetTaskStudent} from '../../config/api'
import HeadingLine from '../common/heading_line'
import Attachment from '../common/attachment'
import AttachmentManagerPro from '../common/attachmentManagerPro'
import styles, {BLUE, borderBottomLine, RED, GREY, LIGHT_GREY, LARGE} from '../../config/styles'
import {PostTaskReplyApi, PutRetractTaskReplyApi} from '../../config/api'

class CorrectingWithBatch extends Component {

    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params
        if (params != undefined) {
            const title = params.title || ''
            const _headerRight = (<TouchableOpacity
                                        style={{paddingRight: 5}}
                                        onPress={params.submit}
                                    >
                                        <Text style={[styles.header_font]}>
                                            {params.status == 'answered' ? '提交' : '撤回'}
                                        </Text>   
                                    </TouchableOpacity>
                                )
            return {
                title: `${title}的作业`,
                headerRight: _headerRight
            }
        }
    } 


    constructor (props) {
        super(props);
        const {params} = props.navigation.state
        this.state = {
            task_id: params.task_id,
            students: params.students,
            status: params.status,
            currentStudentId: params.currentStudentId || params.students[0].id,
            afterReply: params.afterReply,
            homework: {},
            homeworkHistories: [],
            homeworkAudio: {},
            objectForSubmit: {
                attachments: [],
                content: "",
                score: null,
                status: 'accepted'
            }
        }
    }

    componentDidMount () {
        this.props.navigation.setParams({
            title: this.currentStudent().name
        })
        this.getHomework()
       
    }

    //设置顶部操作
    setTitleBtn = () => {
        const {objectForSubmit, students, currentStudentId, afterReply, status, homework} = this.state
        this.props.navigation.setParams({
            status: status,
            submit: () => {
                if (status == 'answered') {
                    if (objectForSubmit.score == null) {
                        Toast.show('请选择评分')
                        return
                    }
    
                    PostTaskReplyApi(objectForSubmit).then((data) => {
                        if (data.code == 0) {
                            afterReply()
                            objectForSubmit.score = 0
                            let _students = students.filter((s, index) => {
                                return s.id != currentStudentId
                            })
                            if (_students.length == 0) {
                                Toast.show('批改完成')
                                this.props.navigation.goBack()
                            } else {
                                Toast.show('自动为您跳转到下个学生')
                                objectForSubmit.score = null
                                this.setState({
                                    students: _students
                                }, () => {
                                    this.switchStudent(_students[0].id)
                                })                            
                            }
                        }
                    })
                } else if (['finished', 'revising'].includes(status)) {
                    PutRetractTaskReplyApi(homework.task_reply.id).then((data) => {
                        if (data.code == 0) {
                            afterReply()
                            Toast.show('撤回成功')
                            this.props.navigation.goBack()
                        }
                    })
                }
            }
        })
    }


    getHomework = () => {
        const {currentStudentId, task_id, objectForSubmit} = this.state
        GetTaskStudent(task_id, currentStudentId).then((data) => {
           
            const currentHomework = data.current_task_answer
            let {attachments} = currentHomework
            let _homeworkAudio
            let _attachments = []
            attachments.forEach((a) => {
                if (a.sub_type == 1) 
                    _homeworkAudio = a
                else                 
                    _attachments.push(a)
            })
            currentHomework.attachments = _attachments
            objectForSubmit.task_answer_id = currentHomework.id
            // data.task_answers.shift()
            this.setState({
                homework: currentHomework,
                homeworkHistories: data.task_answers,
                homeworkAudio: _homeworkAudio
            })
            this.setTitleBtn()
        })
    }

    //附件完成上传之后
    onFinishedUpload = (name, type, awsPath) => {
        let _onDestroy = () => {this.onRemoveAttachment(name)}
        let new_attachment = {
            type: type,
            url: awsPath,
            name: name,
            allowDestroy: true,
            onDestroy: _onDestroy
        }
        let _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.attachments.push(new_attachment)
        this.setState({})
    }

    //点击角标删除attachment的事件
    onRemoveAttachment = (attachment_name) => {
        Alert.alert('删除提醒', '确认要删除这个附件吗？',[
                {text: '取消', onPress: () => {}},
                {text: '确定', onPress: () => {
                    let _attachments = this.state.objectForSubmit.attachments.filter((atta, index) => {
                        return atta.name != attachment_name
                    })
                    let _objectForSubmit = this.state.objectForSubmit
                    _objectForSubmit.attachments = _attachments
                    this.setState({})
                }}
            ]
        )
    }

    currentStudent = () => {
        const {students, currentStudentId} = this.state
        let _student = students.filter((s) => {
            return s.id == currentStudentId
        })[0]
        return _student
    }

    _keyExtractor = (item, index) => index

    _renderItem = ({item}) => {
        const image = item.avatar == null ? (
            item.sex == true ? require('../../assets/images/role-student-male.png') : require('../../assets/images/role-student-female.png')
        ) : {uri: item.avatar}
        //let _width = this.state.currentStudentId == item.id ? 50 : 40
        let _opacity = this.state.currentStudentId == item.id ? 1 : 0.3
        return (
            <TouchableOpacity onPress={() => this.switchStudent(item.id)}>
                <Image source={image} style={{width: 50, height: 50, borderRadius: 25, margin: 5, opacity: _opacity}} />
            </TouchableOpacity>
        )
    }

    _ListHeaderComponent = () => {
        return (
            <View style={{justifyContent: 'center', alignItems: 'center', margin: 5}}>
                <Text>待批 <Text style={{color: 'red'}}>{this.state.students.length}</Text> 人</Text>
            </View>
        )
    }

    switchStudent = (studentId) => {
        if (this.state.currentStudentId == studentId) return
        this.setState({currentStudentId: studentId}, () => {
            this.props.navigation.setParams({
                title: this.currentStudent().name
            });

            this.getHomework()
        })
    }

    setContent = (txt) => {
        const _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.content = txt
        this.setState({})
    }

    setScore = (score) => {
        const _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.score = score
        this.setState({})
    }

    setReplyStatus = () => {
        const _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.status = {'accepted' : 'rejected', 'rejected' : 'accepted'}[_objectForSubmit.status]
        this.setState({})
    }

    correctingTemplate = () => {
        const {students, homeworkAudio, homework, objectForSubmit, status} = this.state
        return(
            <View>
                <View>
                    <View style={{height: 0.3, backgroundColor: borderBottomLine, margin: 5}} />
                
                    <View style={{alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0)', position: 'relative', top: -12}}>
                        <Text style={{backgroundColor: 'white'}}>给出您的评分</Text>
                    </View>   
                </View>
                <View style={{flexDirection: 'row', padding: 10}}>
                    {[1,2,3,4,5].map((n, index) => {
                        return (
                            <TouchableOpacity 
                                style={[styles.score_select_btn, {backgroundColor: n == objectForSubmit.score ? RED : LIGHT_GREY}]} 
                                key={index}
                                onPress={() => this.setScore(n)}
                            >
                                <Text style={styles.text_white}>{n}</Text>
                            </TouchableOpacity>
                        )
                    })}
                </View>

                <View style={{flexDirection: 'row', padding: 10}}>
                    {[6,7,8,9,10].map((n, index) => {
                        return (
                            <TouchableOpacity 
                                style={[styles.score_select_btn, {backgroundColor: n == objectForSubmit.score ? RED : LIGHT_GREY}]} 
                                key={index}
                                onPress={() => this.setScore(n)}
                            >
                                <Text style={styles.text_white}>{n}</Text>
                            </TouchableOpacity>
                        )
                    })}
                </View>

                <View style={{height: 0.3, backgroundColor: borderBottomLine, margin: 5}} />

                <View style={{flex: 1, flexDirection: 'row', padding: 5, alignItems: 'center'}}>
                    <Text style={{flex: 1}}>是否需要订正作业</Text>
                    <Switch
                        onValueChange={this.setReplyStatus}
                        style={{margin: 3}}
                        onTintColor={BLUE}
                        value={objectForSubmit.status == 'rejected'}
                    />
                </View>
            </View>
        )
    }

    render () {
        const {students, homeworkAudio, homework, objectForSubmit, status} = this.state
        console.log('homework', homework)
        return (
            <ScrollView style={{flex: 1}}>
                {status == 'answered' ? (
                    <View style={{flex: 1, flexDirection: 'row', backgroundColor: 'white', marginBottom: 15}}>
                        {this._ListHeaderComponent()}
                        <FlatList 
                            horizontal={true}
                            data={students}
                            keyExtractor={this._keyExtractor}
                            renderItem={this._renderItem}
                            //ListHeaderComponent={this._ListHeaderComponent}
                            style={{backgroundColor: 'white'}}
                        />
                    </View>
                    ) : null
                }
                
                <View style={{flex: 1, backgroundColor: 'white'}}>
                    <HeadingLine title={'作业详情'} collapsible={false} color={BLUE}>
                        <View style={{margin: 10}}>
                            <Attachment attachment={homeworkAudio} />
                        </View>
                        <View style={{height: 0.3, backgroundColor: borderBottomLine, margin: 5}} />
                        <View>
                            <AttachmentManagerPro attachments={homework.attachments} />
                        </View>
                        <View style={{padding: 15}}>
                            <Text style={{paddingBottom: 15}}>学生留言</Text>
                            <Text>{homework.content}</Text>
                        </View>
                    </HeadingLine>
                </View>

                <View style={{flex: 1, backgroundColor: 'white', marginTop: 15}}>
                    <HeadingLine title={'作业点评'} collapsible={false} color={RED} style={{marginTop: 15}}>
                        <View style={{flex: 1, padding: 10}}>
                            {
                                status == 'answered' ? ( 
                                    <TextInput 
                                        style={[styles.background_light_grey_plus, {padding: 0, flex: 1, height: 150}]}
                                        placeholder={'输入您想说的话'}
                                        onChangeText={this.setContent} 
                                        value={objectForSubmit.content}
                                        multiline={true}
                                        textAlignVertical={'top'}
                                    />) : homework.task_reply == undefined ? null : (
                                        <Text>{homework.task_reply.content }</Text>
                                    )
                            }
                           
                        </View>

                        <View>
                            {
                                status == 'answered' ? 
                                    ( <AttachmentManagerPro attachments={objectForSubmit.attachments} onFinishedUpload={this.onFinishedUpload} />)
                                        : homework.task_reply == undefined ? null : (
                                        <AttachmentManagerPro attachments={homework.task_reply.attachments} />
                                    )
                            }
                           
                        </View>

                        {
                            status == 'answered' ? (
                                this.correctingTemplate()
                            ) : ( homework.task_reply == undefined ? null : (
                                <View style={{alignItems: 'center', margin: 10}}>
                                    <Text>
                                        本次作业得分 
                                        <Text style={{color: RED, fontSize: LARGE}}>{homework.task_reply.score}</Text>
                                    </Text>
                                </View>
                            )
                        )
                    }
                      
                        

                      
                    </HeadingLine>
                </View>
                
            </ScrollView>
        )
    }
}

export default CorrectingWithBatch